package com.chenyun.system.controller;


import cn.dev33.satoken.annotation.SaCheckPermission;
import com.chenyun.common.annotation.Log;
import com.chenyun.common.enums.operlog.BusinessTypeEnum;
import com.chenyun.system.model.SysDept;
import com.chenyun.system.service.ISysDeptService;
import com.chenyun.system.vo.TreeSelect;
import com.chenyun.boot.web.controller.BaseController;
import com.chenyun.common.constants.UserConstants;
import com.chenyun.common.utils.StringUtils;
import com.chenyun.common.vo.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * 部门信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/dept")
@Api(tags = "部门信息-admin")
public class SysDeptController extends BaseController<ISysDeptService,SysDept>
{
    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取部门列表
     */
    @ApiOperation("获取部门列表")
    @GetMapping("/list")
    @SaCheckPermission("system:dept:list")
    public AjaxResult list( SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.SUCCESS(depts);
    }

    @ApiOperation("获取部门列表-树形")
    @GetMapping("/listTree")
    @SaCheckPermission("system:dept:listTree")
    public AjaxResult listTree( SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        List<SysDept> sysDepts = deptService.buildDeptTree(depts);
        return AjaxResult.SUCCESS(sysDepts);
    }
    /**
     * 查询部门列表（排除节点）
     */
    @ApiOperation("查询部门列表-排除节点")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext())
        {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId
//                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")
                    )
            {
                it.remove();
            }
        }
        return AjaxResult.SUCCESS(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @ApiOperation("根据部门编号获取详细信息")
    @GetMapping(value = "/{deptId}")
    @SaCheckPermission("system:dept:info")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        deptService.checkDeptDataScope(deptId);
        return AjaxResult.SUCCESS(deptService.selectDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @ApiOperation("获取部门下拉树列表")
    @GetMapping("/treeselect")
    @SaCheckPermission("system:dept:treeselect")
    public AjaxResult treeselect(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.SUCCESS(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 加载对应角色部门列表树
     */
    @ApiOperation("加载对应角色部门列表树")
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    @SaCheckPermission("system:dept:roleDeptTreeselect")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        List<Long> roleIds = deptService.selectDeptListByRoleId(roleId);
        List<TreeSelect> treeSelects = deptService.buildDeptTreeSelect(depts);
        AjaxResult ajax = AjaxResult.SUCCESS(new HashMap<String, Object>(){{
            put("checkedKeys", roleIds);
            put("depts", treeSelects);
        }});
        return ajax;
    }

    /**
     * 新增部门
     */
    @ApiOperation("新增部门")
    @PostMapping
    @Log(title = "新增部门", businessType = BusinessTypeEnum.INSERT)
    @SaCheckPermission("system:dept:add")
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.FAIL("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
//        dept.setCreateBy(SecurityUtils.getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @ApiOperation("修改部门")
    @PostMapping("edit")
    @Log(title = "修改部门", businessType = BusinessTypeEnum.UPDATE)
    @SaCheckPermission("system:dept:edit")
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.FAIL("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(dept.getDeptId()))
        {
            return AjaxResult.FAIL("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus().toString())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0)
        {
            return AjaxResult.FAIL("该部门包含未停用的子部门！");
        }
//        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @ApiOperation("删除部门")
    @PostMapping("del/{deptId}")
    @Log(title = "删除部门", businessType = BusinessTypeEnum.DELETE)
    @SaCheckPermission("system:dept:del")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return AjaxResult.FAIL("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return AjaxResult.FAIL("部门存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }
}
